﻿namespace FlexPlatform.BusinessLogic.DataModel
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq.Expressions;

    using FlexPlatform.GeneralUse;
    using FlexPlatform.Shared.DataModel;
    using FlexPlatform.Shared.Events;
    using FlexPlatform.Shared.Presenters;
    using FlexPlatform.Common;
    using Microsoft.Practices.Unity;
    using FlexPlatform.BusinessLogic.Controllers;

    public abstract class DbEntityBase : IDbEntity
    {
        #region Private Fields

        private IPresenter clsPresenter;
        
        #endregion

        [Key]
        public Guid InternalId { get; set; }

        /// <summary>
        /// Creates a new instance for <see cref="DbEntityBase"/>.
        /// </summary>
        public DbEntityBase()
        {
            InternalId = Guid.NewGuid();
        }

        public event EventHandler<BeforeProperyChangeEventArgs> BeforePropertyChange;
        public event PropertyChangedEventHandler PropertyChanged;

        protected bool TryUpdateProperty<TypeOfOwner, TypeOfValue>(TypeOfOwner propertyOwner, Expression<Func<TypeOfOwner, TypeOfValue>> property, TypeOfValue newValue, ref TypeOfValue originalValue_Container)
        {
            if (!EqualityComparer<TypeOfValue>.Default.Equals(originalValue_Container, newValue))
            {
                string propertyName = ReflectionHelper.GetPropertyName(property);
                var eventArgs = new BeforeProperyChangeEventArgs(this, propertyName, originalValue_Container, newValue);
                if (BeforePropertyChange != null)
                {
                    BeforePropertyChange(this, eventArgs);
                }

                if (!eventArgs.CancelRequested)
                {
                    originalValue_Container = newValue;

                    // the property have been changed. Raise the event.
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                    }
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// Gets a lazy-initialized presenter for this DataEntity. 
        /// </summary>
        public IPresenter Presenter
        {
            get
            {
                // if not created yet, create a controller and a presenter now.
                if (clsPresenter == null)
                {
                    var presenterFactory = SystemGlobal.ServiceLocator.Resolve<IPresenterFactory>();
                    clsPresenter = presenterFactory.BuildEntityPresenter(this);
                }
                return clsPresenter;
            }
        }
    }
}
